package logic

import (
	"context"
	"errors"
	"user-reg-hub/models/cache"
	"user-reg-hub/models/mysql"
	"user-reg-hub/pkg"

	"user-reg-hub/userrpc/internal/svc"
	"user-reg-hub/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	var err error

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误")
	}

	result2, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result2 != in.Captcha {
		return nil, errors.New("图形验证码错误")
	}

	if err = user.FindUserByAccount(mysql.DB, in.Account); err != nil {
		user = mysql.User{
			Account:  in.Account,
			Password: in.Password,
		}
		if err = user.UserCreate(mysql.DB); err != nil {
			return nil, errors.New("用户注册失败")
		}
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, errors.New("密码错误，登录失败")
	}

	cache.Rdb.Del(l.ctx, "SendSms"+in.SendSms)
	cache.Rdb.Del(l.ctx, "captcha"+in.Account)

	return &userrpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
